<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Grid\Detail;
use App\Admin\Repositories\ReturnPerformance;
use App\Enums\DataPermission;
use App\Enums\OptionType;
use App\Enums\ReturnChannel;
use App\Enums\ReturnStage;
use App\Enums\UserStatus;
use App\Models\User;
use App\Services\OptionService;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;

class ReturnPerformanceController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid(): Grid
    {
        return Grid::make(new ReturnPerformance(), function (Grid $grid) {
            $data_permission_is_all = $this->getAdminDataPermission() == DataPermission::ALL;

            $grid->model()
                ->with(['customer', 'user', 'doctor'])
                ->when(!$data_permission_is_all, function (Builder $builder) {
                    $builder->where('user_id', self::getUserId());
                })
                ->orderByDesc('id');
            $grid->column('customer.name', trans('customer.fields.name'));
            $grid->column('customer.phone', trans('customer.fields.phone'));
            $grid->column('user.name', trans('return-performance.fields.user_id'));
            $grid->column('money');
            $grid->column('disease');
            $grid->column('stage')->display(function ($value) {
                return ReturnStage::getDescription($value);
            });
            $grid->column('subsidy');
            $grid->column('doctor.name', trans('return-performance.fields.doctor_option_id'));
            $grid->column('remark');
            $grid->column('created_at');

            $grid->filter(function (Grid\Filter $filter) {
                $filter->like('customer.name', trans('customer.fields.name'));
                $filter->like('customer.phone', trans('customer.fields.phone'));
                $filter->like('user.name', trans('return-performance.fields.user_id'));
                $filter->equal('stage')->select(ReturnStage::asSelectArray());
            });

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->append(new Detail());
            });

            $grid->disableCreateButton();
            if ($data_permission_is_all) {
                $grid->showQuickEditButton();
            } else {
                $grid->disableDeleteButton();
            }
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    public function detail(int $id): Show
    {
        return Show::make($id, ReturnPerformance::with(['customer', 'user', 'doctor']), function (Show $show) {
            $show->field('customer.name', trans('customer.fields.name'));
            $show->field('customer.phone', trans('customer.fields.phone'));
            $show->field('user.name', trans('return-performance.fields.user_id'));
            $show->field('doctor.name', trans('return-performance.fields.doctor_option_id'));
            $show->field('disease');
            $show->field('money');
            $show->field('pay_images')->as(function () {
                return $this->getPayImages();
            })->image();
            $show->field('stage')->as(function ($value) {
                return ReturnStage::getDescription($value);
            });
            $show->field('delivery');
            $show->field('drug');
            $show->field('treatment_course');
            $show->field('subsidy');
            $show->field('invitation_user_ids')->as(function ($value) {
                return $value ? join('，', User::query()->whereIn('id', json_decode($value))->pluck('name')->toArray()) : '';
            });
            $show->field('consultant_user_ids')->as(function ($value) {
                return $value ? join('，', User::query()->whereIn('id', json_decode($value))->pluck('name')->toArray()) : '';
            });

            $show->field('channel')->as(function ($value) {
                return ReturnChannel::getDescription($value);
            });
            $show->field('channel_date');
            $show->field('consultation');
            $show->field('remark');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form(): Form
    {
        return Form::make(new ReturnPerformance(), function (Form $form) {

            $form->text('disease')->maxLength(100);
            $form->number('money')->min(1)->max(999999)->required();
            $form->select('stage')->options(ReturnStage::asSelectArray())->required();
            $form->text('delivery');
            $form->text('drug');
            $form->text('treatment_course');
            $form->number('subsidy')->min(1)->max(999999)->required();
            $form->multipleSelect('invitation_user_ids')->options(User::query()->where('status', UserStatus::WORKING)->pluck('name', 'id'));
            $form->multipleSelect('consultant_user_ids')->options(User::query()->where('status', UserStatus::WORKING)->pluck('name', 'id'));
            $form->select('doctor_option_id')->options(OptionService::getOption(OptionType::DOCTOR))->required();
            $form->select('channel')->options(ReturnChannel::asSelectArray());
            $form->datetime('channel_date');
            $form->datetime('consultation');
            $form->multipleImage('pay_images_str', trans('sale-performance.fields.pay_images'))->default($form->model()->getPayImages(), true)->move('images/' . date('Y') . '/' . date('m') . '/' . date('d'))->retainable()->uniqueName()->autoUpload();
            $form->hidden('pay_images');
            $form->textarea('remark');
            $form->saving(function (Form $form) {
                $form->pay_images = '';
                if (request('pay_images_str')) {
                    $images = explode(',', request('pay_images_str'));
                    foreach ($images as $key => $value) {
                        if (filter_var($value, FILTER_VALIDATE_URL) !== false) {
                            $images[$key] = Str::replace(getAliOssDomain(), '', Arr::first(explode('?', $value)));
                        }
                    }
                    $form->pay_images = json_encode($images);
                }
                $form->disease = $form->disease ?: '';
                $form->delivery = $form->delivery ?: '';
                $form->drug = $form->drug ?: '';
                $form->treatment_course = $form->treatment_course ?: '';
            });
            $form->ignore(['pay_images_str']);
        });
    }
}
